package j.util.pkgenerator;

import j.util.DateUtils;

import java.util.Date;

/**
 * User: jason
 * Date: 13-4-18 上午10:44
 */
class NextValue {

    public synchronized int getNext(PG pgInstance,String key){
        PkGeneratorService service = pgInstance.getService();
        /*if(isRecountingByDay()){
            //每天都需要将序号重置为0
            Date now = new Date();
            if(!DateUtils.isSameDay(getLastRetriveDate(), now)){
                //上次获取时间与当前不是同一天了，需要重置为0
                System.out.println("需要设为0");
                setLastRetriveDate(now);
                setBeginIndex(0);
                setNextMaxIndex(service.getAndUpdateGenValue(key,now));
            }
        }*/
        beginIndex+=1;
        if(beginIndex>getNextMaxIndex()){
            NextValue nextValue = service.generateNextValueByKey(key);
            System.out.println("nextValue:"+nextValue.getBeginIndex()+","+nextValue.getNextMaxIndex());
            setNextValue(nextValue);
            //nextValue = instance.map.get(key);
            beginIndex = nextValue.getBeginIndex()+1;
        }
        return beginIndex;
    }

    private String prefix;
    private int beginIndex;
    private int nextMaxIndex;
    private boolean recountingByDay;
    private Date lastRetriveDate;
    private int allocationSize;
    private int length;
    private String dateFormat;

    public String getPrefix() {
        return prefix;
    }
    public void setPrefix(String prefix) {
        this.prefix = prefix;
    }

    public int getBeginIndex() {
        return beginIndex;
    }
    public void setBeginIndex(int beginIndex) {
        this.beginIndex = beginIndex;
    }

    public int getNextMaxIndex() {
        return nextMaxIndex;
    }
    public void setNextMaxIndex(int nextMaxIndex) {
        this.nextMaxIndex = nextMaxIndex;
    }

    public boolean isRecountingByDay() {
        return recountingByDay;
    }
    public void setRecountingByDay(boolean recountingByDay) {
        this.recountingByDay = recountingByDay;
    }

    public Date getLastRetriveDate() {
        return lastRetriveDate;
    }
    public void setLastRetriveDate(Date lastRetriveDate) {
        this.lastRetriveDate = lastRetriveDate;
    }

    public void setNextValue(NextValue nextValue) {
        beginIndex = nextValue.getBeginIndex();
        nextMaxIndex = nextValue.getNextMaxIndex();
        lastRetriveDate = nextValue.getLastRetriveDate();
    }

    public int getAllocationSize() {
        return allocationSize;
    }
    public void setAllocationSize(int allocationSize) {
        this.allocationSize = allocationSize;
    }

    int getLength() {
        return length;
    }
    void setLength(int length) {
        this.length = length;
    }

    String getDateFormat() {
        return dateFormat;
    }
    void setDateFormat(String dateFormat) {
        this.dateFormat = dateFormat;
    }
}
